package com.iss.card.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.internal.co;
import com.iss.card.R;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;

/**
 * �����࣬���һЩ�����ķ���
 */
public class Tools {
	private static final String TAG = Tools.class.getSimpleName();

	/**
	 * ���ͼƬ��ַ
	 */
	public static String groupImageUrl(String startUrl, String endUrl) {
		StringBuffer s = new StringBuffer();
		s.append(startUrl);
		s.append(endUrl);
		return s.toString();
	}

	/**
	 * ��ʾ��Ϣ
	 */
	public static void showToast(Context c, String val) {

		if (TextUtils.isEmpty(val)) {
			return;
		}
		Toast.makeText(c, val, Toast.LENGTH_SHORT).show();
	}

	/**
	 * ��ʾ��Ϣ
	 */
	public static void showToast(Context c, int val) {

		Toast.makeText(c, val, Toast.LENGTH_SHORT).show();
	}

	/**
	 * Dialog�û�ѡ��ʽ��ʾ
	 * 
	 * @param context
	 * @param message
	 *            ��ʾ��Ϣ
	 * @param okListener
	 *            ȷ����ť
	 * @param cancelListener
	 *            ȡ��ť
	 */
	public static void showDialog(Activity context, int message,
			DialogInterface.OnClickListener okListener,
			DialogInterface.OnClickListener cancelListener) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message);
		builder.setTitle(R.string.dialog_title_name);
		builder.setPositiveButton(R.string.dialog_but_ok, okListener);
		builder.setNegativeButton(R.string.dialog_but_cancel, cancelListener);
		Dialog dialog = builder.create();
		dialog.setCanceledOnTouchOutside(false);// ���� ���dialog�ⲿ����ʧ��
		dialog.show();
	}

	/**
	 * �ж������Ƿ����
	 * 
	 * @param context
	 * @return boolean.
	 */
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * it is used to open sub view in setting page. the following are class for
	 * sub views in setting page. </p>　
	 * com.android.settings.AccessibilitySettings 辅助功能设置 </p>
	 * 　　com.android.settings.ActivityPicker 选择活动 </p>
	 * 　　com.android.settings.ApnSettings APN设置 </p>
	 * 　　com.android.settings.ApplicationSettings 应用程序设置 </p>
	 * 　　com.android.settings.BandMode 设置GSM/UMTS波段 </p>
	 * 　　com.android.settings.BatteryInfo 电池信息 </p>
	 * 　　com.android.settings.DateTimeSettings 日期和坝上旅游网时间设置 </p>
	 * 　　com.android.settings.DateTimeSettingsSetupWizard 日期和时间设置 </p>
	 * 　　com.android.settings.DevelopmentSettings 应用程序设置=》开发设置 </p>
	 * 　　com.android.settings.DeviceAdminSettings 设备管理器 </p>
	 * 　　com.android.settings.DeviceInfoSettings 关于手机 </p>
	 * 　　com.android.settings.Display 显示——设置显示字体大小及预览 </p>
	 * 　　com.android.settings.DisplaySettings 显示设置 </p>
	 * 　　com.android.settings.DockSettings 底座设置 </p>
	 * 　　com.android.settings.IccLockSettings SIM卡锁定设置 </p>
	 * 　　com.android.settings.InstalledAppDetails 语言和键盘设置 </p>
	 * 　　com.android.settings.LanguageSettings 语言和键盘设置 </p>
	 * 　　com.android.settings.LocalePicker 选择手机语言 </p>
	 * 　　com.android.settings.LocalePickerInSetupWizard 选择手机语言 </p>
	 * 　　com.android.settings.ManageApplications 已下载（安装）软件列表 </p>
	 * 　　com.android.settings.MasterClear 恢复出厂设置 </p>
	 * 　　com.android.settings.MediaFormat 格式化手机闪存 </p>
	 * 　　com.android.settings.PhysicalKeyboardSettings 设置键盘 </p>
	 * 　　com.android.settings.PrivacySettings 隐私设置 </p>
	 * 　　com.android.settings.ProxySelector 代理设置 </p>
	 * 　　com.android.settings.RadioInfo 手机信息 </p>
	 * 　　com.android.settings.RunningServices 正在运行的程序（服务） </p>
	 * 　　com.android.settings.SecuritySettings 位置和安全设置 </p>
	 * 　　com.android.settings.Settings 系统设置 </p>
	 * 　　com.android.settings.SettingsSafetyLegalActivity 安全信息 </p>
	 * 　　com.android.settings.SoundSettings 声音设置 </p>
	 * 　　com.android.settings.TestingSettings 测试——显示手机信息、电池信息、使用情况统计、Wifi
	 * information、服务信息 </p> 　　com.android.settings.TetherSettings 绑定与便携式热点 </p>
	 * 　　com.android.settings.TextToSpeechSettings 文字转语音设置 </p>
	 * 　　com.android.settings.UsageStats 使用情况统计 </p>
	 * 　　com.android.settings.UserDictionarySettings 用户词典 </p>
	 * 　　com.android.settings.VoiceInputOutputSettings 语音输入与输出设置 </p>
	 * 　　com.android.settings.WirelessSettings 无线和网络设置 </p>
	 * 
	 * @param ct
	 *            context
	 * @param cls
	 *            class for sub view. please refer the above description.
	 */
	public static boolean openSetting(Context ct, String cls) {
		Intent intent;
		//判断手机系统的版本  即API大于10 就是3.0或以上版本 
        if(android.os.Build.VERSION.SDK_INT>10){
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
            intent.setAction("android.intent.action.VIEW");
        }else{
            intent = new Intent();
            ComponentName cm = new ComponentName(CommonValue.PACKAGE_SETTING, "com.android.phone.Settings");
    		intent.setComponent(cm);
    		intent.setAction("android.intent.action.VIEW");
		
			try{
			((Activity) ct).startActivityForResult(intent,
					ApplicationManager.REQCODE_NETWORK_SETTING);
			} catch (Exception e) {
				return false;
			}
		}
		return true;
	}

	/**
	 * �����ٶȺ���
	 */
	public static void showNetworkSpeedIsSnail(Activity c, boolean sp) {
		if (sp) {
			showToast(c, R.string.network_speed_is_snail);
		}
	}

	/**
	 * show error log.
	 * 
	 * @param tv
	 * @param preStr
	 * @param redStr
	 */
	public static void showErrorLog(TextView tv, String preStr, String redStr) {
		tv.setVisibility(View.VISIBLE);
		tv.setText(Html.fromHtml(preStr + "<font color='red'>" + redStr
				+ "</font>"));
	}

	/**
	 * �������ӣ��������ʧ�ܵȴ�����ʽ����.
	 * 
	 * @param type
	 * @param bError
	 * @param envelope
	 * @param mContext
	 * @param tv
	 * @return
	 */
	public static boolean onPostCheck(int type, Object result,
			Activity mContext, TextView tv, int index) {
		Resources r = mContext.getResources();
		switch (type) {
		case CommonValue.ErrorType.TYPE_CANCLE:
			Tools.showErrorLog(tv, r.getString(R.string.data_found_error),
					r.getString(R.string.data_found_again));
			return true;
		case CommonValue.ErrorType.TYPE_NETWORK:
			Tools.showErrorLog(tv, r.getString(R.string.network_error),
					r.getString(R.string.network_refresh));
			return true;
		default:
			break;
		}

		if (result == null) {
			// show error 1
			Tools.showErrorLog(tv, r.getString(R.string.data_found_error),
					r.getString(R.string.data_found_again));
			return true;
		}
		// else if(result.equals("")){
		// Tools.showErrorLog(tv,r.getString(R.string.data_found_error),r.getString(R.string.data_found_again));
		// return false;
		// }
		return false;
	}

	public static boolean onPostCheck(Context context, ResponseBean response) {
		if (response == null) {
			return true;
		}
		if (response.getStatus() != null
				&& ApplicationManager.RESPONSE_OK.equals(response.getStatus())) {
			return false;
		} else {
			Tools.showToast(context, response.getMessage());
		}
		return true;
	}

	public static void onPostCheck(Activity context, TextView tv) {
		Resources r = context.getResources();
		Tools.showErrorLog(tv, r.getString(R.string.data_is_empty), "");
	}

	// /**
	// * get current city by gps.
	// * @param c
	// */
	// public static void openGPSSettings(Activity c) {
	// LocationManager alm = (LocationManager) c
	// .getSystemService(Context.LOCATION_SERVICE);
	// if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER))
	// {
	// getLocationInfo(c);
	// return;
	// }
	// // Toast.makeText(c, "�뿪��GPS��", Toast.LENGTH_SHORT).show();
	// Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	// c.startActivityForResult(intent,0); //��Ϊ������ɺ󷵻ص���ȡ����
	// }
	/**
	 * get current city name by gps.
	 * 
	 * @param c
	 */
	private static void getLocationInfo(Activity c) {
		String str = "";
		LocationManager locationManager = (LocationManager) c
				.getSystemService(Context.LOCATION_SERVICE);

		Criteria criteria = new Criteria();
		// �����õĶ�λЧ��
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(false);
		// ʹ��ʡ��ģʽ
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		// ��õ�ǰ��λ���ṩ��
		String provider = locationManager.getBestProvider(criteria, true);
		// ��õ�ǰ��λ��
		Location location = locationManager.getLastKnownLocation(provider);
		if (location == null) {
			Log.e(TAG, "getLocationInfo:location = " + location);
			return;
		}
		Geocoder gc = new Geocoder(c);
		List<Address> addresses = null;
		try {
			addresses = gc.getFromLocation(location.getLatitude(),
					location.getLongitude(), 1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "getLocationInfo:IOException");
			e.printStackTrace();
		}
		if (addresses != null && addresses.size() > 0) {
			str += "AddressLine��" + addresses.get(0).getAddressLine(0) + "\n";
			str += "CountryName��" + addresses.get(0).getCountryName() + "\n";
			str += "Locality��" + addresses.get(0).getLocality() + "\n";
			str += "FeatureName��" + addresses.get(0).getFeatureName();
		}
		Log.e(TAG, str);
	}

	// add by qiubo at 2013-03-21 begin
	/**
	 * @author qiubo
	 * @category �ȥ��س������У��Ʊ����ַ�
	 * @param str
	 *            :��Ҫ�滻��Ԫ�ַ�
	 * @return dest : ȥ��س������У��Ʊ����ַ����ַ�
	 * @serialData��2013-03-19
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * @author qiubo
	 * @category жϴ����ַ��Ƿ�Ϊ�ֻ���� ���ƶ�����ͨ,����
	 * @param str
	 *            :�ַ�
	 * @return boolean : �Ƿ�Ϊ�ֻ����
	 * @serialData��2013-03-21
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	// add by qiubo at 2013-03-21 end

	public static String triableDesDecode() {
		StringBuilder sb = null;

		return sb.toString();

	}

	/**
	 * 3DES ����
	 * 
	 * @param src
	 * @return
	 */
	public static String triableEncode(String src) {
		byte[] encodeByte = null;
		String stringForRe = null;
		java.security.Key javaKey = null;
		byte[] byteForRe = null;

		try {
			encodeByte = src.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			SecretKeyFactory keyFactory = SecretKeyFactory
					.getInstance("DESede");
			DESedeKeySpec spec = new DESedeKeySpec(
					ApplicationManager.TRIBLEDES_SECURITY);
			Cipher cipher = Cipher
					.getInstance(ApplicationManager.TRIABLE_DES_ALGORITHM);
			javaKey = keyFactory.generateSecret(spec);
			// SecretKey secretKey = keyFactory.generateSecret(spec);
			cipher.init(Cipher.ENCRYPT_MODE, javaKey);
			byteForRe = cipher.doFinal(encodeByte);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		stringForRe = Base64.encodeToString(byteForRe, Base64.DEFAULT);

		return stringForRe;
	}

	public static class TimeCount extends CountDownTimer {
		private TextView btn;
		private Context mContext;

		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			// TODO Auto-generated constructor stub
		}

		public TimeCount(Context context, long millisInFuture,
				long countDownInterval, TextView registerCaptchaButton) {
			super(millisInFuture, countDownInterval);
			this.btn = registerCaptchaButton;
			this.mContext = context;

		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			btn.setClickable(true);
			btn.setText(mContext.getString(R.string.account_getcaptcha_text));
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// TODO Auto-generated method stub
			btn.setClickable(false);
			int second = (int) (millisUntilFinished / 1000);
			btn.setText(String.format(
					mContext.getString(R.string.reminder_time), second));
		}

	}

	public static void showToast(PostExecute postExecute, String message) {
		// TODO Auto-generated method stub

	}
}
